package com.ktwlsoft.archivemanage.domain.business.businessService;

import com.alibaba.fastjson.JSONObject;
import com.ktwlsoft.archivemanage.config.exception.ResultException;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.*;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.ImgsService;
import com.ktwlsoft.archivemanage.domain.dao.entity.*;
import com.ktwlsoft.archivemanage.domain.dao.entity.Imgs;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import com.ktwlsoft.archivemanage.payload.archiveUnit.ArchiveUnitManageAddRequest;
import com.ktwlsoft.archivemanage.payload.archiveUnit.ArchiveUnitManageUpdateRequest;
import com.ktwlsoft.archivemanage.payload.archiveUnit.UploadFileInfo;
import com.ktwlsoft.archivemanage.payload.operationLog.SaveLogRequest;
import com.ktwlsoft.archivemanage.service.utils.SnowFlake;
import com.ktwlsoft.archivemanage.service.utils.UserUtils;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * @description         立档单位管理业务层服务类
 * @author              chenkun
 * @version             1.0
 * @date                2019-10-28
 */
@Service
public class ArchiveUnitBusinessService {

    Logger logger=LoggerFactory.getLogger(ArchiveUnitBusinessService.class);

    @Autowired
    private ArchiveUnitRepositoryService archiveUnitRepositoryService;

    @Autowired
    private UnitMemberRepositoryService unitMemberRepositoryService;

    @Autowired
    private InfrastructureRepositoryService infrastructureRepositoryService;

    @Autowired
    private InforConstRepositoryService inforConstRepositoryService;

    @Autowired
    private ImgsService imgsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AccountRepositoryService accountRepositoryService;

    /**
     * @description     查询立档单位的所有信息
     * @param           unitId 立档单位id
     * @return          Result
     */
    @Transactional(rollbackFor = Exception.class)
    public Result findAllInformationById(Long unitId){
        if(unitId == null){
            return Result.body(null,ResultType.BUSINESS_ERROR).withMessage("立档单位信息不存在");
        }
        ArchiveUnitDetail archiveUnitDetail=archiveUnitRepositoryService.findArchiveUnitInfoById(unitId);
        UnitMember unitMember= (UnitMember) unitMemberRepositoryService.findUnitMemberInfoById(unitId).getData();
        InforConst inforConst= (InforConst) inforConstRepositoryService.findInforConstItem(unitId).getData();
        Infrastructure infrastructure= (Infrastructure) infrastructureRepositoryService.findInfrastructureInfo(unitId).getData();
        List<Imgs> imagesList=imgsService.findImagesByBusinessId(unitId);
        if(imagesList != null && imagesList.size() > 0){
            for (Imgs item:imagesList) {
                String imgPath=ImgUploadService.getImagePath(item.getUrl());
                item.setUrl(imgPath);
            }
        }
        Map<String,Object> resultMap=new HashMap<String,Object>();
        resultMap.put("archiveUnitDetail",archiveUnitDetail);
        resultMap.put("unitMember",unitMember);
        resultMap.put("inforConst",inforConst);
        resultMap.put("infrastructure",infrastructure);
        resultMap.put("imagesList",imagesList);
        ArchiveUnit unit = archiveUnitRepositoryService.getById(unitId);
        OperationRepositoryService.saveLog(new SaveLogRequest(
                OperationLog.OperationType.CHECK,
                "查看立档单位《"+ unit.getUnitName() +"》",
                "立档单位",
                OperationLog.BusinessType.BUSINESS
        ));
        return Result.body(resultMap,ResultType.BUSINESS_SUCCESS);
    }
    /**
     * @description     新增立档单位信息
     * @param           request
     * @return          Result
     */
    @Transactional(rollbackFor = Exception.class)
    public Result addArchiveUnitInfo(ArchiveUnitManageAddRequest request){
        String initialPassword="Ywzd000111%@@";
        Long parentId=request.getArchiveUnitAddRequest().getPid();
        /**立档单位情况**/
        ArchiveUnit archiveUnit=new ArchiveUnit();
        BeanUtils.copyProperties(request.getArchiveUnitAddRequest(),archiveUnit);
        archiveUnit.setPassword(passwordEncoder.encode(initialPassword));
        archiveUnit.setTreeLevel(1);/**一级立档单位层级为1**/
        /**验证立档单位名称是否重复**/
        Integer count=archiveUnitRepositoryService.findByUnitName(archiveUnit.getUnitName());
        if(null != count && count.intValue() > 0){
            return Result.body(null,ResultType.CHECK_ERROR).withMessage("立档单位名称已存在");
        }
        /**检查账号和手机号的唯一性**/
        Account checkUnique=new Account();
        checkUnique.setTeleNum(request.getUnitMemberAddRequest().getRecorderTele());
        checkUnique.setRoleName("立档单位");
        List<Account> accounts= accountRepositoryService.checkUnique(checkUnique);
        if(accounts != null && accounts.size() > 0){
            for(Account account:accounts){
                if(account.getUserName().equals(request.getArchiveUnitAddRequest().getAccount())){
                    return Result.body(request,ResultType.CHECK_ERROR).withMessage("账号重复");
                }
                if(account.getTeleNum().equals(request.getUnitMemberAddRequest().getRecorderTele())){
                    return Result.body(request,ResultType.CHECK_ERROR).withMessage("手机号重复");
                }
            }
        }
        try{
            /**获取前端上传的文件列表**/
            List<UploadFileInfo> filesList=request.getFiles();
            /**存在上传文件,按businessType分类后再上传**/
            List<Imgs> handledImgs = new ArrayList<>();
            if(filesList != null && filesList.size() > 0){
                Map<String,List<MultipartFile>> filesMap=classifyBybusinessType(filesList);
                /**处理上传文件**/
                handledImgs = handleUploadImages(filesMap,String.valueOf(archiveUnit.getId()),null);
            }
            /**找出单位头像的地址*/
            String unitImg = "";
            String memberFile = "";
            for (Imgs img : handledImgs) {
                if ("unitFile".equals(img.getBusinessType())) {
                    unitImg = img.getId().toString();
                }
                if ("memberFile".equals(img.getBusinessType())) {
                    memberFile = img.getId().toString();
                }
            }
            /**写入账户数据**/
            Account accountSave=new Account();
            accountSave.setUserName(request.getArchiveUnitAddRequest().getAccount());
            accountSave.setRealName(request.getUnitMemberAddRequest().getRecorder());
            accountSave.setTeleNum(request.getUnitMemberAddRequest().getRecorderTele());
            Boolean sex=request.getUnitMemberAddRequest().getRecorderSex();
            if(sex == null){
                accountSave.setSex(true);
            }else {
                accountSave.setSex(sex);
            }
            accountSave.setIdentityType("IDCARD");
            accountSave.setIdentityNum(request.getUnitMemberAddRequest().getRecorderIdentityNum());
            accountSave.setEnable(request.getArchiveUnitAddRequest().getEnable());
            accountSave.setPassword(passwordEncoder.encode(initialPassword));
            accountSave.setPasswordStrength(UserUtils.testingPasswordStrength(initialPassword));
            accountSave.setRoleId(0l);
            accountSave.setRoleName("立档单位");
            accountSave.setProfile(memberFile);
            accountRepositoryService.insert(accountSave);
            archiveUnit.setAccountId(accountSave.getId());
            /**上级立档单位**/
            if(null != parentId && !"".equals(parentId)){
                archiveUnit.setPid(parentId);
                archiveUnit.setTreeLevel(2);/**二级立档单位为2**/
            }
            archiveUnit.setUnitImg(unitImg);
            archiveUnitRepositoryService.addArchiveUnitInfo(archiveUnit);
            /**增加人员信息、信息化建设、基础设施**/
            addOtherInformation(request,archiveUnit.getId(), accountSave.getId(),memberFile);
        }catch (Exception e){
            logger.info(e.getMessage());
            e.printStackTrace();
            throw new ResultException(e.getMessage(),ResultType.SAVING_ERROR);
        }
        return  Result.body(archiveUnit.getId(),ResultType.BUSINESS_SUCCESS).withMessage("添加立档单位成功");

    }

    /**
     * @description 更新立档单位信息
     * @param request
     * @return Result
     */
    @Transactional(rollbackFor = Exception.class)
    public Result updateArchiveUnitInfo(ArchiveUnitManageUpdateRequest request){
        List<UploadFileInfo> deleteFilesList=request.getDeleteFiles();
        Long unitId=request.getUnitId();
        Long parentId=request.getArchiveUnitUpdateRequest().getPid();
        if(unitId == null){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("立档单位信息不存在");
        }
        /**立档单位信息**/
        ArchiveUnit archiveUnit=new ArchiveUnit();
        BeanUtils.copyProperties(request.getArchiveUnitUpdateRequest(),archiveUnit);
        archiveUnit.setTreeLevel(1);/**默认树层级为1**/
        archiveUnit.setId(unitId);

        /**上级立档单位信息**/
        if(null != parentId && !"".equals(parentId)){
            archiveUnit.setPid(parentId);
            archiveUnit.setTreeLevel(2);/**如果指定上级立档单位,则树层级为2**/
        }
        ArchiveUnitDetail archiveUnitDetail=archiveUnitRepositoryService.findArchiveUnitInfoById(archiveUnit.getId());
        try{
            /**存在上传文件,按businessType分类后再上传**/
            List<UploadFileInfo> filesList=request.getFiles();
            Map<String,List<MultipartFile>> filesMap=classifyBybusinessType(filesList);
            /**处理上传文件**/
            List<Imgs> handledImgs = handleUploadImages(filesMap,request.getBusinessId(),deleteFilesList);
            /**找出单位头像的地址*/
            String unitImg = "";
            /**找出人员头像的地址*/
            String profile = "";
            for (Imgs img : handledImgs) {
                if ("unitFile".equals(img.getBusinessType())) {
                    unitImg = img.getId().toString();
                }
                if ("memberFile".equals(img.getBusinessType())) {
                    profile = img.getId().toString();
                }
            }
            if (!"".equals(unitImg)) {
                archiveUnit.setUnitImg(unitImg);
            }
            if (!"".equals(profile)) {
                request.getUnitMemberUpdateRequest().setProfile(profile);
            }
            archiveUnitRepositoryService.updateArchiveUnitInfo(archiveUnit);
            /**检查用户名和手机号的唯一性**/
            Account checkUnique=new Account();
            checkUnique.setTeleNum(request.getUnitMemberUpdateRequest().getRecorderTele());
            checkUnique.setRoleName("立档单位");
            List<Account> accounts= accountRepositoryService.checkUnique(checkUnique);
            if(accounts != null && accounts.size() > 0){
                for(Account account:accounts){
                    if(!account.getId().equals(request.getArchiveUnitUpdateRequest().getAccountId())){
                        if(account.getUserName().equals(request.getUnitMemberUpdateRequest().getRecorder())){
                            return Result.body(request,ResultType.CHECK_ERROR).withMessage("账号重复");
                        }
                        if(account.getTeleNum().equals(request.getUnitMemberUpdateRequest().getRecorderTele())){
                            return Result.body(request,ResultType.CHECK_ERROR).withMessage("手机号重复");
                        }
                    }
                }
            }
            /**更新账户信息**/
            Account account=new Account();
            account.setId(archiveUnitDetail.getAccountId());
            account.setEnable(request.getArchiveUnitUpdateRequest().getEnable());
            account.setRealName(request.getUnitMemberUpdateRequest().getRecorder());
            account.setTeleNum(request.getUnitMemberUpdateRequest().getRecorderTele());
            account.setProfile(request.getUnitMemberUpdateRequest().getProfile());
            Boolean sex=request.getUnitMemberUpdateRequest().getRecorderSex();
            if(null == sex){
                account.setSex(true);
            }else{
                account.setSex(sex);
            }
            account.setIdentityNum(request.getUnitMemberUpdateRequest().getRecorderIdentityNum());
            accountRepositoryService.update(account);
            /**更新人员信息、信息化建设、基础设施**/
            updateOtherInformation(request);
        }catch (Exception e){
            logger.info(e.getMessage());
            e.printStackTrace();
            throw new ResultException(e.getMessage(),ResultType.SAVING_ERROR);
        }
        return Result.body(archiveUnit.getId(), ResultType.BUSINESS_SUCCESS).withMessage("更新立档单位信息成功");
    }
    /**
     * @description     删除立档单位信息
     * @param           unitId 立档单位id
     * @return          Result
     */
    @Transactional(rollbackFor = Exception.class)
    public Result deleteArchiveUnitInfo(Long unitId,Long businessId){
        if(unitId == null){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("立档单位信息不存在");
        }
        try{
            ArchiveUnitDetail archiveUnitInfo=archiveUnitRepositoryService.findArchiveUnitInfoById(unitId);
            /**查询是否有下级立档单位,如果有,递归删除所有下级立档单位**/
            List<ArchiveUnitDetail> list=archiveUnitRepositoryService.findSubArchiveUnitList(unitId);
            if(list != null && list.size() > 0){
                for(ArchiveUnitDetail archiveUnitDetail:list){
                    deleteArchiveUnitInfo(archiveUnitDetail.getId(),businessId);
                }
            }
            archiveUnitRepositoryService.deleteArchiveUnitInfo(unitId);
            unitMemberRepositoryService.deleteUnitMemberInfo(unitId);
            infrastructureRepositoryService.deleteInfrastructureInfo(unitId);
            inforConstRepositoryService.deleteInforConstItem(unitId);
            ImgUploadService.deleteByBusinessId(businessId);
            accountRepositoryService.deleteById(archiveUnitInfo.getAccountId());
        }catch (Exception e){
            logger.info(e.getMessage());
            e.printStackTrace();
            throw new ResultException(e.getMessage(),ResultType.DELETE_ERROR);
        }
        return Result.body(unitId, ResultType.BUSINESS_SUCCESS).withMessage("删除立档单位信息成功");
    }

    /**
     * @description     创建立档单位的其他信息
     * @param           request
     * @param           unitId 立档单位id
     */
    @Transactional(rollbackFor = Exception.class)
    public void addOtherInformation(ArchiveUnitManageAddRequest request, Long unitId, Long accountId,String memberFile){
        /**立档单位人员信息**/
        UnitMember unitMember=new UnitMember();
        BeanUtils.copyProperties(request.getUnitMemberAddRequest(),unitMember);
        unitMember.setUnitId(unitId);
        unitMember.setDepartLeaderId(SnowFlake.getNextId());
        unitMember.setRecorderId(accountId);
        unitMember.setProfile(memberFile);

        /**信息化建设**/
        InforConst inforConst=new InforConst();
        BeanUtils.copyProperties(request.getInforConstAddRequest(),inforConst);
        inforConst.setUnitId(unitId);

        /**基础设施信息**/
        Infrastructure infrastructure=new Infrastructure();
        BeanUtils.copyProperties(request.getInfrastructureAddRequest(),infrastructure);
        infrastructure.setUnitId(unitId);

        unitMemberRepositoryService.addUnitMemberInfo(unitMember);
        inforConstRepositoryService.addInforConstItem(inforConst);
        infrastructureRepositoryService.addInfrastructureInfo(infrastructure);
    }

    /**
     * @description     更新立档单位的其他信息
     * @param           request
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateOtherInformation(ArchiveUnitManageUpdateRequest request){
        /**立档单位人员信息**/
        UnitMember unitMember=new UnitMember();
        BeanUtils.copyProperties(request.getUnitMemberUpdateRequest(),unitMember);
        unitMember.setUnitId(request.getUnitId());

        /**信息化建设**/
        InforConst inforConst=new InforConst();
        BeanUtils.copyProperties(request.getInforConstUpdateRequest(),inforConst);
        inforConst.setUnitId(request.getUnitId());

        /**基础设施信息**/
        Infrastructure infrastructure=new Infrastructure();
        BeanUtils.copyProperties(request.getInfrastructureUpdateRequest(),infrastructure);
        infrastructure.setUnitId(request.getUnitId());

        unitMemberRepositoryService.updateUintMemberInfo(unitMember);
        inforConstRepositoryService.updateInforConstItem(inforConst);
        infrastructureRepositoryService.updateInfrastructureInfo(infrastructure);
    }

    /**
     * @description 处理图片上传
     * @param filesMap 文件列表
     * @param businessId 业务编号
     * @param deleteFilesList 要删除的文件列表
     */
    private List<Imgs> handleUploadImages(Map<String,List<MultipartFile>> filesMap,
                                    String businessId,
                                    List<UploadFileInfo> deleteFilesList){
        List<Imgs> imgs = new ArrayList<>();
        /**取得业务类型对应的文件列表**/
        if(filesMap != null && filesMap.size() > 0){
            for (Map.Entry<String,List<MultipartFile>> entry:filesMap.entrySet()) {
                List<Imgs> tempImgs = new ArrayList<>();
                String businessType=entry.getKey();
                List<MultipartFile> filesList=entry.getValue();
                if(filesList != null && filesList.size() > 0) {
                    tempImgs = ImgUploadService.imgUpload(filesList, businessId, businessType);
                }
                imgs.addAll(tempImgs);
            }
        }
        /**删除需要更新的图片**/
        if(deleteFilesList != null && deleteFilesList.size() > 0){
            List<Long> imgIdList=new ArrayList<>();
            List<String> imgUrlList=new ArrayList<>();
            for(UploadFileInfo uploadFileInfo:deleteFilesList){
                imgIdList.add(uploadFileInfo.getFileId());
                imgUrlList.add(uploadFileInfo.getFileUrl());
                ImgUploadService.deleteById(uploadFileInfo.getFileId());
            }
            imgsService.deleteByIds(imgIdList);
            ImgUploadService.deleteExistedFiles(imgUrlList);
        }
        return imgs;
    }

    /**
     * @description 按业务类型对文件进行分类
     * @param filesList
     * @return Map<String,List<MultipartFile>>
     */
    private Map<String,List<MultipartFile>> classifyBybusinessType(List<UploadFileInfo> filesList){
        Map<String,List<MultipartFile>> filesMap=new HashMap<>();
        if(filesList != null && filesList.size() > 0){
            for(UploadFileInfo uploadFileInfo:filesList){
                List<MultipartFile> subFilesList=new ArrayList<>();
                String businessType=uploadFileInfo.getBusinessType();
                if(filesMap.containsKey(businessType)){
                    filesMap.get(businessType).add(uploadFileInfo.getFile());
                }else{
                    subFilesList.add(uploadFileInfo.getFile());
                    filesMap.put(businessType,subFilesList);
                }
            }
        }
        return filesMap;
    }

    /**
      * 立档单位下拉查询 on 2019/11/13 17:32
      *
      * @param keyWords keyWords
      * @return Result<?>
      */
    @Transactional(rollbackFor = Exception.class)
    public Result<?> findListAll(String keyWords){
        JSONObject object = new JSONObject();
        object.put("enable",1);
        object.put("keyWords",keyWords != null?keyWords:null);
        List<JSONObject> list = archiveUnitRepositoryService.findListAll(object);
        if(list != null && list.size() > 0){
            for(JSONObject jsonObject:list){
                UnitMember unitMember = unitMemberRepositoryService.getByUnitId(jsonObject.getLong("id"));
                JSONObject unitMemberJson = new JSONObject();
                if(unitMember != null){
                    unitMemberJson.put("id",unitMember.getId());
                    unitMemberJson.put("recorder",unitMember.getRecorder());
                    unitMemberJson.put("recorderId",unitMember.getRecorderId());
                    unitMemberJson.put("recorderTele",unitMember.getRecorderTele());
                }
                jsonObject.put("unitMember",unitMemberJson);
            }
        }
        return Result.ok(list);
    }
}
